package com.neoharvest.smartagri;

import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import com.neoharvest.smartagri.command.impl.StartHarvestCommand;
import com.neoharvest.smartagri.decorator.impl.GpsTrackingDecorator;
import com.neoharvest.smartagri.factory.AgriculturalMachineFactory;
import com.neoharvest.smartagri.factory.impl.SmartAgriMachineFactory;
import com.neoharvest.smartagri.facade.SmartAgriFacade;
import com.neoharvest.smartagri.model.AgriculturalMachine;
import com.neoharvest.smartagri.observer.EnvironmentObserver;
import com.neoharvest.smartagri.observer.impl.SoilMoistureSensor;
import com.neoharvest.smartagri.proxy.impl.SmartMachineProxy;
import com.neoharvest.smartagri.service.*;
import com.neoharvest.smartagri.state.impl.WorkingState;
import com.neoharvest.smartagri.strategy.impl.EfficientPathStrategy;

public class Main {
    private static List<AgriculturalMachine> machines = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        System.out.println("NeoHarvest 新穗农业助手启动中");
        initializeServices();
        showMainMenu();
    }
    
    private static void initializeServices() {
        // 初始化服务
        FieldMonitoringService monitoringService = new FieldMonitoringService();
        PathPlanningService pathService = new PathPlanningService();
        TaskManagementService taskService = new TaskManagementService();
        SystemManagementService systemService = new SystemManagementService();
        
        // 添加示例农机
        AgriculturalMachineFactory factory = new SmartAgriMachineFactory();
        machines.add(factory.createSeederMachine());
        machines.add(factory.createSprayerMachine());
        machines.add(factory.createHarvesterMachine());
    }
    
    private static void showMainMenu() {
        while (true) {
            System.out.println("\n==== NeoHarvest 新穗 ====");
            System.out.println("1. 显示所有农机状态");
            System.out.println("2. 模拟环境数据变化");
            System.out.println("3. 触发紧急事件");
            System.out.println("4. 添加新农机");
            System.out.println("5. 查看任务队列");
            System.out.println("6. 查看环境数据历史");
            System.out.println("7. 查看农机日志");
            System.out.println("8. 多农机协同作业");
            System.out.println("9. 退出");
            System.out.print("请选择操作: ");
            
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    showMachineStatus();
                    break;
                case 2:
                    simulateEnvironmentChange();
                    break;
                case 3:
                    triggerEmergency();
                    break;
                case 4:
                    addNewMachine();
                    break;
                case 5:
                    showTaskQueue();
                    break;
                case 6:
                    showEnvironmentHistory();
                    break;
                case 7:
                    showMachineLogs();
                    break;
                case 8:
                    simulateCooperativeTask();
                    break;
                case 9:
                    System.out.print("确认退出系统？(Y/N): ");
                    String confirm = scanner.next();
                    if (confirm.equalsIgnoreCase("Y")) {
                        System.out.println("系统退出...");
                        return;
                    }
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }
        
    private static void showMachineStatus() {
        System.out.println("\n=== 农机状态 ===");
        for (int i = 0; i < machines.size(); i++) {
            AgriculturalMachine machine = machines.get(i);
            System.out.println("ID: " + machine.getClass().getSimpleName() + "-" + (i+1));
            System.out.println("状态: " + machine.getStatus());
            System.out.println("位置: " + machine.getPosition());
            System.out.println("油量: " + machine.getFuelLevel());
            System.out.println("----------------");
        }
    }
    
    private static void simulateEnvironmentChange() {
        FieldMonitoringService monitoringService = new FieldMonitoringService();
        Random random = new Random();
        
        double moisture = 50 + random.nextInt(30);
        double pH = 6.0 + random.nextDouble() * 1.5;
        double nutrient = 5.0 + random.nextInt(5);
        
        monitoringService.updateSoilData("moisture", moisture);
        monitoringService.updateSoilData("pH", pH);
        monitoringService.updateSoilData("nutrient", nutrient);
        
        System.out.println("\n环境数据已更新:");
        System.out.println("湿度: " + moisture + "%");
        System.out.println("pH值: " + pH);
        System.out.println("养分: " + nutrient + "级");
        
        // 环境变化响应
        if (moisture > 70) {
            System.out.println("[通知] 检测到高湿度(" + moisture + "%)，农机将调整工作模式");
        } else if (moisture < 40) {
            System.out.println("[警告] 检测到低湿度(" + moisture + "%)，建议增加灌溉");
        }
    }
    
    private static void triggerEmergency() {
        if (machines.isEmpty()) {
            System.out.println("没有可用的农机！");
            return;
        }
        
        System.out.println("\n[警报] 检测到紧急事件！");
        
        for (AgriculturalMachine machine : machines) {
            System.out.println("\n处理 " + machine.getClass().getSimpleName() + "-" + 
                             (machines.indexOf(machine)+1) + ":");
            System.out.println("[处理] 启动紧急制动...");
            
            // 更新位置
            Random rand = new Random();
            int x = rand.nextInt(20);
            int y = rand.nextInt(20);
            machine.updatePosition(x + "," + y);
            
            System.out.println("[处理] 路径重规划中...");
            machine.executeTask();
            System.out.println("[完成] 紧急任务已执行，新位置: " + machine.getPosition());
            System.out.println("剩余油量: " + machine.getFuelLevel());
        }
    }
    
    private static void showTaskQueue() {
        System.out.println("\n=== 任务队列 ===");
        for (AgriculturalMachine machine : machines) {
            String status = "等待中";
            if (machine.getStatus().equals("工作中")) {
                status = "执行中 (进度: " + new Random().nextInt(100) + "%)";
            } else if (machine.getStatus().equals("暂停")) {
                status = "暂停";
            }
            System.out.println(machine.getClass().getSimpleName() + "-" + 
                             (machines.indexOf(machine)+1) + ": " + 
                             machine.getCurrentTask() + " (" + status + ")");
        }
    }
    
    private static void showEnvironmentHistory() {
        System.out.println("\n=== 土壤湿度记录 ===");
        System.out.println("2023-05-01 09:00: 65%");
        System.out.println("2023-05-01 12:00: 71% ↑");
        System.out.println("2023-05-01 15:00: 68% ↓");
    }
    
    private static void showMachineLogs() {
        System.out.println("\n=== 农机操作日志 ===");
        for (AgriculturalMachine machine : machines) {
            System.out.println(machine.getClass().getSimpleName() + "-" + 
                             (machines.indexOf(machine)+1) + " 日志:");
            System.out.println("[05-01 14:30] " + machine.getCurrentTask() + 
                             " (位置: " + machine.getPosition() + ") 耗油: " + 
                             (100-machine.getFuelLevel()) + "L");
        }
    }
    
    private static void simulateCooperativeTask() {
        System.out.println("\n[协同任务] 区域B2:");
        for (AgriculturalMachine machine : machines) {
            String status = machine.getStatus().equals("工作中") ? 
                          "执行中" : "准备就绪";
            System.out.println("- " + machine.getClass().getSimpleName() + "-" + 
                             (machines.indexOf(machine)+1) + ": " + status);
        }
        System.out.println("[完成] 协同任务已开始执行");
    }
    
    private static void addNewMachine() {
        AgriculturalMachineFactory factory = new SmartAgriMachineFactory();
        
        System.out.println("\n选择农机类型:");
        System.out.println("1. 播种机");
        System.out.println("2. 喷雾机");
        System.out.println("3. 收割机");
        System.out.print("请选择: ");
        
        int type = scanner.nextInt();
        AgriculturalMachine newMachine = null;
        
        switch (type) {
            case 1:
                newMachine = factory.createSeederMachine();
                newMachine.updateFuelLevel(100); // 确保初始油量
                newMachine.updatePosition("0,0"); // 重置位置
                break;
            case 2:
                newMachine = factory.createSprayerMachine();
                newMachine.updateFuelLevel(100);
                newMachine.updatePosition("0,0");
                break;
            case 3:
                newMachine = factory.createHarvesterMachine();
                newMachine.updateFuelLevel(100);
                newMachine.updatePosition("0,0");
                break;
            default:
                System.out.println("无效选择！");
                return;
        }
        
        machines.add(newMachine);
        System.out.println("新农机 " + newMachine.getClass().getSimpleName() + "-" + machines.size() + " 添加成功！");
        System.out.println("初始状态: 油量=100, 位置=0,0");
    }
}